// 创建类收集依赖
class Depend {
    constructor() {
        this.reactiveFns = []
        // 执行一次
        // this.reactiveFns = new set()
    }
    addDepend(fn) {
        if (fn) {
            this.reactiveFns.push(fn)
            // this.reactiveFns.add(fn)
        }
    }
    notify() {
        this.reactiveFns.forEach(fn => {
            fn()
        })
    }
}
const obj = {
    name: "ran",
    age: 18
}

// 创建类
let reactiveFn = null
function watchFn(fn) {
    reactiveFn = fn
    fn()
    reactiveFn = null
}
// 封装一个函数：负责通过obj的key获取对应depend对象
const objMap = new WeakMap()
function getDepend(obj, key) {
    // 1.根据对象obj，找到对应的map对象
    let map = objMap.get(obj)
    if (!map) {
        map = new Map()
        objMap.set(obj,map)
    }
    // 2.根据key，找到对应的denpenf对象
    let dep = map.get(key)
    if (!dep) {
        dep = new Depend()
        map.set(key,dep)
    }
    return dep
}
// 方案一：Object.defineProperty() vue2
Object.keys(obj).forEach(key => {
    let value = obj[key]
    Object.defineProperty(obj, key, {
        set: function (newValue) {
            value = newValue
            const dep = getDepend(obj, key)
            dep.notify()
        },
        get: function () {
            const dep = getDepend(obj, key)
            dep.addDepend(reactiveFn)
            return value
        }
    })
})
watchFn(function foo() {
    console.log("foo:", obj.name);
    console.log("foo:", obj.age);
    console.log("foo function",);
})

watchFn(function bar() {
    console.log("bar:", obj.age + 10);
    console.log("bar function",);
})

// console.log("name发生变化-------------");
// obj.name = "kobe"
console.log("age发生变化--------------");
obj.age = 10
// console.log("name再次变化--------------");
// obj.name = "bill"